import React, { useEffect, useState } from 'react';
import { View, Text, Pressable, StyleSheet, TextInput, Alert, TouchableOpacity, FlatList, Dimensions, ScrollView, ImageBackground, Image } from 'react-native';
import { format } from 'date-fns';
import FontAwesome from 'react-native-vector-icons/FontAwesome5';
import { Calendar } from 'react-native-calendars';
import { Root, Popup } from 'popup-ui'
import "../global.css"
import axios from "axios"
import { Link } from 'expo-router';
// import { createDrawerNavigator } from '@react-navigation/drawer';



interface Task {
  id: string;
  title: string;
  completed: boolean;
  date: string;
}

interface TaskMenuProps {
  taskId: string;
  onClose: () => void;
  onEdit: () => void;
  onDelete: () => void;
}

interface CharacterMenuProps {
  taskId: string;
  onClose: () => void;
  onEdit: () => void;
  onDelete: () => void;
}


const TaskMenu: React.FC<TaskMenuProps> = ({ taskId, onClose, onEdit, onDelete }) => {
  return (
    <View style={styles.taskMenuContainer}>
      <Pressable
        onPress={onEdit}
        className="px-4 py-2 text-left text-sm text-gray-700"
      >
        <FontAwesome name="edit" size={16} color="#718096" style={{ marginRight: 4 }} />
      </Pressable>
      <Pressable
        onPress={onDelete}
        className="px-4 py-2 text-left text-sm text-red-600"
      >
        <FontAwesome name="trash-alt" size={16} color="#E53E3E" style={{ marginRight: 4 }} />
      </Pressable>
    </View>
  );
};


//Drawer之后再写吧
// const Drawer = createDrawerNavigator();
// function CustomDrawerContent(props:any) {
//   return (
//     <View style={{ flex: 1, padding: 20 }}>
//       <Text style={{ fontSize: 24, fontWeight: 'bold', marginVertical: 20 }}>我的应用</Text>
//       <Button
//         title="主页"
//         onPress={() => props.navigation.navigate('Home')}
//       />
//       <Button
//         title="设置"
//         onPress={() => props.navigation.navigate('Settings')}
//       />
//     </View>
//   );
// }

const App: React.FC = () => {
  //语言设置（先是静态的）
  const language = {
    zh: {
      language: "中文",
      title: '待办事项',
      todayTasks: '今日任务',
      clearCompleted: '清理完成事项',
      addTask: '新建任务',
      editTask: '修改任务',
      edit: '修改',
      delete: '删除',
      cancel: '取消',
      confirm: '确定',
      placeholder: '请输入任务内容',
      message: '这个小东西会在你添加事项后回复你',
      loading: '小东西思考中',
      success: '清理完成',
      successMessage: '今日はお疲れさまでした',
      ok: 'Ok',
      character: [
        {
          name:"小东西",
          message: "这个小东西会在你添加事项后回复你"
        },
        {
          name:"烤炉",
          message: "我是烤炉"
        }
      ]
    },
    en: {
      language: "English",
      title: 'To-Do List',
      todayTasks: 'Today\'s Tasks',
      clearCompleted: 'Clear Completed Tasks',
      addTask: 'Add Task',
      editTask: 'Edit Task',
      edit: 'Edit',
      delete: 'Delete',
      cancel: 'Cancel',
      confirm: 'Confirm',
      placeholder: 'Enter task content',
      message: 'This little thing will reply after you add a task',
      loading: 'Thinking...',
      clearSuccess: 'Clear Completed',
      successMessage: 'Good job!',
      ok: 'Ok',
      character: [
        {
          name:"little thing",
          message: "This little thing will reply after you add a task"
        },
        {
          name:"Kaworu Nagisa",
          message: "im Kaworu Nagisa,wanna shechdule the 3rd impact(why)"
        }
      ]
    },
  };
  const [currentLanguage, setCurrentLanguage] = useState(language.en);
  const [tasks, setTasks] = useState<Task[]>([
    {
      id: '1',
      title: 'task1',
      completed: false,
      date: '2024-01-15'
    },
    {
      id: '2',
      title: 'task2',
      completed: true,
      date: '2024-01-15'
    },
  ]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedCharacter, setSelectedCharacter] = useState(1)
  const [newTaskTitle, setNewTaskTitle] = useState('');
  const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]);
  const [editingTask, setEditingTask] = useState<Task | null>(null);
  const [activeMenu, setActiveMenu] = useState<string | null>(null);
  const [showMenu,setShowMenu] = useState(true)
  const [isClear, setIsClear] = useState(false)
  const [message, setMessage] = useState(currentLanguage.character[selectedCharacter].message)
  const [isLoading, setIsloading] = useState(false)
  const bgImages = [
    require('../assets/images/0.png'),
    require('../assets/images/1.png'),
    // 添加更多图片路径
  ];
  const CharacterMenu= () => {
    return (
      <View style={styles.characterMenuContainer}>
        {currentLanguage.character.map((c:any,index)=>(<Pressable key={index}
          onPress={()=>{
            setSelectedCharacter(index)
            setMessage(c.message); // 更新消息
            console.log(selectedCharacter)
          }}
        ><Text>{c.name}</Text></Pressable>))}
      </View>
    );
  };
  //改变任务状态
  const toggleTaskStatus = async (taskId: any) => {
    let changedTask = ''
    let completed = false
    setTasks(tasks.map(task => {
      if (task.id === taskId) {
        changedTask = task.title
        completed = task.completed
      }
      return task.id === taskId ? { ...task, completed: !task.completed } : task
    }
    ));
    console.log(changedTask)
    await sendMessage(changedTask, completed ? "完成" : "未完成")
  };

  //添加/修改任务
  const addOrUpdateTask = async () => {
    if (newTaskTitle.trim()) {
      if (editingTask) {
        setTasks(tasks.map(task =>
          task.id === editingTask.id
            ? { ...task, title: newTaskTitle }
            : task
        ));
      } else {
        const newTask: Task = {
          id: Date.now().toString(),
          title: newTaskTitle,
          completed: false,
          date: format(selectedDate, 'yyyy-MM-dd')
        };
        setTasks([...tasks, newTask]);
      }
      setNewTaskTitle('');
      setIsModalOpen(false);
      setEditingTask(null);
      await sendMessage(newTaskTitle, "添加/修改")
    }
  };

  const handleEditTask = (task: Task) => {
    setEditingTask(task);
    setNewTaskTitle(task.title);
    setIsModalOpen(true);
    setActiveMenu(null);
  };

  const handleDeleteTask = (taskId: string) => {
    setTasks(tasks.filter(task => task.id !== taskId));
    setActiveMenu(null);
  };

  const clearCompletedTasks = () => {
    setIsClear(true)
    setTimeout((() => {
      setTasks(tasks.filter(task => !task.completed));
      setIsClear(false)
      Popup.show({
        type: 'Success',
        title: currentLanguage.clearSuccess,
        textBody: currentLanguage.successMessage,
        buttonText: 'Ok',
        callback: () => Popup.hide()
      })
    }), 2000)

  };

  const sendMessage = async (title: string, action: string) => {
    try {
      setIsloading(true)
      console.log(selectedCharacter)
      const response = await axios.post(' http://172.16.8.163:5000/chat', {
        "message": title,
        "action": action,
        "characterId":selectedCharacter,
        "language":currentLanguage.language
      }, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      if (response.data.response != undefined) {
        console.log(response.data.response)
        setMessage(response.data.response)
        setIsloading(false)
      }

    } catch (error: any) {
      console.log(error)
    }
  }
  return (
    <Root>
      <ScrollView>

        <View className="relative min-h-screen bg-gradient-to-b from-amber-200 to-white">
          {/* Nav Bar */}
          {/* <Link href="/test">About</Link> */}
          <View className="fixed top-0 w-full bg-amber-300 shadow-sm z-50 px-4 py-4 flex flex-row justify-between">
            <Pressable className="w-1/4"
            onPress={()=>setShowMenu(!showMenu)}><FontAwesome name="bars" size={24} color="white" /></Pressable>
            <Text className="text-lg font-medium text-center text-white">{currentLanguage.title}</Text>
            <Pressable
              onPress={() =>{
                let lan=currentLanguage.language=== 'zh'? language.en:language.zh as any;
                setCurrentLanguage(lan)
              }}
              className='bg-amber-50 rounded-lg flex justify-center w-1/4'
            >
              <Text className=" text-sm font-medium text-center text-amber-300">{currentLanguage.language === 'zh' ? 'Switch to en' : '切换到中文'}</Text>
            </Pressable>
          </View>
          <View>{showMenu&&<CharacterMenu/>}</View>
          {/* Calendar Section */}
          <Calendar
            theme={{
              textSectionTitleColor: '#b6c1cd',
              selectedDayBackgroundColor: '#fcd34d',
              selectedDayTextColor: '#ffffff',
              todayTextColor: '#00adf5',
              dayTextColor: '#2d4150',
              textDisabledColor: '#cbd5e1',
            }}
            onDayPress={(day: any) => {
              console.log('Selected day:', day);
              setSelectedDate(day.dateString);
            }}
            markedDates={{
              [selectedDate]: { selected: true },
            }}
          />
          {/* ai回复展示区 */}
          <View className='w-full h-52'>
            <ImageBackground
              source={bgImages[selectedCharacter]}
              resizeMode="stretch" // 控制图片的缩放模式
              className='h-full'
            >
              <View className='w-full h-full flex justify-start items-start px-10 py-7'>
                <Text className="text-base font-medium">{isLoading ? (currentLanguage.loading) : (message)}</Text>
              </View>
            </ImageBackground>
          </View>
          {/* Task List */}
          <View className="mt-4 px-4 pb-24">
            <View className="flex flex-row justify-between items-center mb-4">
              <Text className="text-base font-medium">{currentLanguage.todayTasks}</Text>
              <Pressable
                onPress={clearCompletedTasks}
                className="px-3 py-1.5 text-amber-500 text-xs border border-amber-400 rounded-full flex items-center hover:bg-amber-50 transition-colors !rounded-button"
              >
                <FontAwesome name="broom" size={14} color="#F6AD55" style={{ marginRight: 4 }} />
                {isClear ? (<Text>clearing</Text>) : (<Text>{currentLanguage.clearCompleted}</Text>)}
              </Pressable>
            </View>
            {tasks.filter(task => task.date === selectedDate).map((task) => (
              <View
                key={task.id}
                className="flex flex-row items-center bg-white p-4 rounded-lg mb-3 shadow-sm relative -z-10"
              >
                <Pressable
                  onPress={() => toggleTaskStatus(task.id)}
                  className={`w-6 h-6 rounded-full border-2 flex items-center justify-center
              ${task.completed ? 'border-amber-300 bg-amber-300' : 'border-gray-300'}`}
                >
                  {task.completed && <FontAwesome name="check" size={14} color="white" />}
                </Pressable>
                <View className="flex-1 ml-3">
                  <Text className={`text-base ${task.completed ? 'line-through text-gray-400' : 'text-gray-800'}`}>
                    {task.title}
                  </Text>
                  <Text className="text-xs text-gray-400 mt-1">{task.date}</Text>
                </View>
                <Pressable
                  onPress={() => setActiveMenu(activeMenu === task.id ? null : task.id)}
                  className="p-2"
                >
                  <FontAwesome name="ellipsis-v" size={16} color="#718096" />
                </Pressable>
                {activeMenu === task.id && (
                  <TaskMenu
                    taskId={task.id}
                    onClose={() => setActiveMenu(null)}
                    onEdit={() => handleEditTask(task)}
                    onDelete={() => handleDeleteTask(task.id)}
                  />
                )}
              </View>
            ))}
          </View>

          {/* Add Task FAB */}
          <Pressable
            onPress={() => setIsModalOpen(true)}
            className="fixed bottom-6 left-1/2 transform -translate-x-1/2 w-14 h-14 bg-amber-300 rounded-full shadow-lg flex items-center justify-center hover:bg-amber-400 transition-colors !rounded-button"
          >
            <FontAwesome name="plus" size={20} color="white" />
          </Pressable>

          {/* 添加弹窗*/}
          {isModalOpen && (
            <View style={styles.modalOverlay}>
              <View className="bg-white w-[90%] rounded-lg p-6">
                <Text className="text-lg font-medium mb-4">
                  {editingTask ? currentLanguage.editTask : currentLanguage.addTask}
                </Text>
                <TextInput
                  value={newTaskTitle}
                  onChangeText={(text) => setNewTaskTitle(text)}
                  placeholder={currentLanguage.placeholder}
                  className="w-full h-14 px-4 py-2 border-none bg-amber-50 rounded-lg mb-4 text-sm focus:outline-none focus:ring-2 focus:ring-amber-300"
                />
                <View className="flex flex-row justify-end space-x-3">
                  <Pressable
                    onPress={() => {
                      setIsModalOpen(false);
                      setEditingTask(null);
                      setNewTaskTitle('');
                    }}
                    className="px-4 py-2 text-gray-600 !rounded-button"
                  >
                    <Text>{currentLanguage.cancel}</Text>
                  </Pressable>
                  <Pressable
                    onPress={addOrUpdateTask}
                    className="px-4 py-2 bg-amber-300 text-white rounded-lg hover:bg-amber-400 transition-colors !rounded-button"
                  >
                    <Text>{currentLanguage.confirm}</Text>
                  </Pressable>
                </View>
              </View>
            </View>
          )}

        </View>

      </ScrollView>
    </Root>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F9FAFB',
    justifyContent: 'center',
    alignItems: 'center',
  },
  taskMenuContainer: {
    position: 'absolute',
    right: 0,
    top: 8,
    backgroundColor: 'white',
    borderRadius: 8,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 5,
    zIndex: 1000, // 确保层级最高
    width: 128,
    paddingVertical: 8,
    display: "flex",
    flexDirection: "row",
    justifyContent: "space-between"
  },
  characterMenuContainer: {
    position: 'absolute',
    left: 0,
    top: 8,
    backgroundColor: 'white',
    borderRadius: 8,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 5,
    zIndex: 1000, // 确保层级最高
    width: 128,
    paddingVertical: 8,
    display: "flex",
    flexDirection: "column",
  },
  modalOverlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },

});
export default App;